package com.example.demo.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.core.handler.exception.ResultBO;
import com.example.demo.core.handler.exception.ResultTool;
import com.example.demo.sys.service.UserService;
import com.example.demo.sys.service.bo.UserBO;
import com.example.demo.web.config.JwtConfig;
import com.example.demo.web.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtConfig jwtConfig;

    @PostMapping("/login")
    @ResponseBody
    public ResultBO<?> login(@RequestBody LoginVO loginDTO) {
        UserBO user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
        JSONObject json = new JSONObject();
        if (user != null) {
            String userId = user.getId().toString();
            String token = jwtConfig.createToken(userId);
            if (StringUtils.hasLength(token)) {
                json.put("token", token);
            }
        }
        return ResultTool.success(json);
    }
}
